﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using it_security_project.App_Code.BusinessLogicLayer;

namespace it_security_project
{
    public partial class ForumThread : System.Web.UI.Page
    {

        public new Site site { get { return base.Master as Site; } }


        private Captcha c;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GenerateCaptcha();
            }
            try
            {
                int navigatedThreadID = int.Parse(Request.QueryString["thread"]);

                Service service = new Service();

                Thread currentThread = service.GetThreadById(navigatedThreadID);

                TitleLabel.Text = "Title: " + currentThread.Title;
                AuthorLabel.Text = "Author: " + currentThread.Author;
                TitleContentLabel.Text = currentThread.Topic;
                TitleContentLabel.Enabled = false;

                Member member = site.LoginWithSession();
                if (member == null)
                {
                    PanelNewComment.Visible = false;
                    PanelNewComment.Enabled = false;
                }
            }
            catch
            {
                TitleLabel.Text = "A thread has not been chosen";
                PanelNewComment.Visible = false;
                TitleContentLabel.Visible = false;
                PanelNewComment.Enabled = false;
                TitleContentLabel.Enabled = false;
            }
        }

        private void GenerateCaptcha()
        {
            c = new CaptchaGenerator().GetCaptcha();

            ImageCaptacha.ImageUrl = c.ImageURL;
            FUUUSK.Text = c.Name;
        }

        protected void newCommentBtn_Click(object sender, EventArgs e)
        {
            if (TextBoxCaptcha.Text.ToLower() == FUUUSK.Text.ToLower())
            {
                int userID = site.GetMemberID();
                if (userID != -1) // -1 = error
                {
                    int threadID = int.Parse(Request.QueryString["thread"]);
                    string comment = newCommentTextBox.Text;
                    Service service = new Service();
                    service.AddComment(userID, comment, threadID);
                    service.GetCommentsOnThreadId(threadID.ToString());
                    service.AddLog(userID, "Added comment: " + comment);
                    Response.Redirect("~/ForumThread.aspx?thread=" + Request.QueryString["thread"]);
                }
            }
            else
            {
                site.ChangeCustomMessage("Captcha WRONG!",MessageType.Error);
            }
        }
    }
}